import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BladeContainerBase } from '../../../../../shared/blade/blade-container-base';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { BladeData } from '../../../../../shared/blade/blade-data';
import { Blade } from '../../../../../shared/blade/blade.model';
import { Command } from '../../../../../shared/toolbar.service';
import { TagMapService } from '../../../../../service/tag-map.service';
import { TagMap } from '../../../../../entity/tag-map.model';
import { Tag } from '../../../../../entity/tag.model';
import { MatrixStateGroup } from '../../../../../entity/matrix-state-group.model';
import { MatrixLogicGroup } from '../../../../../entity/matrix-logic-group.model';
import { TagService } from '../../../../../service/tag.service';
@Component({
  selector: 'app-tag-map-edit',
  templateUrl: './tag-map-edit.component.html',
  styleUrls: ['./tag-map-edit.component.css']
})
export class TagMapEditComponent extends BladeContainerBase<TagMap> {
  @Output() clearText = new EventEmitter<boolean>();

  /**
   * 测点集合
   * 
   * @type {Tag[]}
   * @memberof TagMapEditComponent
   */
  tags: Tag[];

  /**
   * 过滤后的测点集合
   * 
   * @type {Tag[]}
   * @memberof TagMapEditComponent
   */
  results: Tag[];

  /**
   * 当前测点名称
   * 
   * @type {string}
   * @memberof TagMapEditComponent
   */
  brand: string;

  /**
   * 过滤后的测点名称集合
   * 
   * @type {string[]}
   * @memberof TagMapEditComponent
   */
  tagData: string[];

  /**
   * 状态组集合
   * 
   * @type {MatrixStateGroup[]}
   * @memberof TagMapEditComponent
   */
  msGroups: MatrixStateGroup[] = [];

  /**
   * 逻辑组集合
   * 
   * @type {MatrixLogicGroup[]}
   * @memberof TagMapEditComponent
   */
  mlGroups: MatrixLogicGroup[] = [];

  filterMLGroups: MatrixLogicGroup[] = [];
  currentTag: Tag;
  constructor(
    private fb: FormBuilder,
    private tagMapService: TagMapService,
  ) {
    super(fb);
  }

  ngOnInit() {
    let tags: Tag[] = [];
    this.parentEntity.tags.forEach(tag => {
      let i = this.parentEntity.tagMaps.findIndex(o => o.tagId == tag.tagId);
      if (i == -1) {
        tags.push(tag);
      }
    });
    if (!this.isNew) {
      this.commands = [
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ];
      //状态组
      this.msGroups = this.parentEntity.msGroups.filter(o => o.tagId == this.currentEntity.tagId);
      if (this.currentEntity.stateGroupId && this.msGroups && this.mlGroups.length) {
        //逻辑组
        this.filterMLGroups = this.parentEntity.mlGroups.filter(o => o.stateGroupId == this.currentEntity.stateGroupId);
      }

      const i = this.parentEntity.tags.findIndex(o => o.tagId == this.currentEntity.tagId);
      if (i > -1) {
        tags.push(this.parentEntity.tags[i]);
        this.currentTag = this.parentEntity.tags[i];
        this.brand = this.parentEntity.tags[i].tagName;
      }

    }
    this.results = [...tags];
    this.tagData = this.results.map(o => o.tagName);
    this.tags = tags;
    super.ngOnInit();
  }
  initData(): any | Observable<any> | Promise<any> {
    this.formPatchValue(this.currentEntity);
  }
  exeSaveChange(blade: any): void {
    this.saveChange();
  }
  canSaveChange(blade: any): boolean {
    return (this.hasChange() || (this.tags.findIndex(o => o && (o.tagName == this.brand)) > -1) && this.brand.split('-')[0] != this.currentEntity.tagName) && !this.hasError();
  }
  exeReset(blade: any): void {
    this.brand = this.currentTag.tagName;
    return this.formGroup.reset(this.currentEntity);
  }
  canReset(blade: any): boolean {

    return this.hasChange() || this.brand != this.currentTag.tagName;
  }
  createForm() {
    let obj: {} = {
      'tagstateMark': [this.currentEntity.tagstateMark],
      // 'tagstateMark': this.currentEntity.tagstateMark,
      'stateGroupId': this.currentEntity.stateGroupId,//状态
      'logicGroupId': this.currentEntity.logicGroupId,//逻辑
      'faultTag': this.currentEntity.faultTag,//是否故障
      'tagMapSeq': this.currentEntity.tagMapSeq,//排序
      'unShow': this.currentEntity.unShow//是否显示

    };
    this.formGroup = this.fromBuider.group(obj);
    this.formGroup.controls['stateGroupId'].valueChanges.subscribe(form => {
      this.filterMLGroups = [];
      if (form) {
        this.filterMLGroups = this.parentEntity.mlGroups.filter(o => o.stateGroupId == form);
      }
    })
  }
  /**
  * 设置表单错误对象
  * 
  * 
  * @memberof BladeContainerBase
  */
  setFormError(): void {
    this.formErrors = {
      'tagId': '',
    };
  }
  /**
  * 设置表单验证信息
  * 
  * 
  * @memberof BladeContainerBase
  */
  setValidationMessages(): void {
    this.validationMessages = {
      'tagId': {
        'required': '测点名称不能为空',
        'maxlength': '测点名称不能多于20个字符长度。',
      },
    };
  }

  /**
   * 创建一个测点信息
   * 
   * 
   * @memberof TurbstatusEditComponent
   */
  onCreate() {
    if (!this.hasError()) {

      this.changeCurrent();
      this.tagMapService.create(this.currentEntity)
        .then(res => {

          if (res) {

            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(this.parentEntity.current);
            this.bladeService.closeBlade(this.currentBlade);
          } else {

            throw new Error('数据新增失败！')
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);

    }
  }
  /**
   * 
   * 
   * 
   * @memberof TagsEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {

    if (this.canSaveChange(this.currentBlade)) {
      this.changeCurrent();
      return this.tagMapService.update(this.currentEntity)
        .then(res => {
          if (res) {
            this.clearText.emit(true);
            (this.parentBlade.bladeContainerInstance).refresh(this.parentEntity.current);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
          throw new Error('数据更新失败！')

        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }
  changeCurrent() {
    //this.bladeData.isLoading = true;
    let index = this.results.findIndex(o => o.tagName == this.brand);
    if (index <= -1) return false;
    this.currentEntity.tagId = this.results[index].tagId;
    let formValue = this.formGroup.value;
    this.currentEntity.tagstateMark = formValue.tagstateMark;
    this.currentEntity.stateGroupId = formValue.stateGroupId ? formValue.stateGroupId : null;
    if (!this.currentEntity.stateGroupId) {
      this.currentEntity.logicGroupId = null;
    } else {
      this.currentEntity.logicGroupId = formValue.logicGroupId ? formValue.logicGroupId : null;
    }

    this.currentEntity.faultTag = formValue.faultTag;
    this.currentEntity.tagMapSeq = formValue.tagMapSeq;
    this.currentEntity.unShow = formValue.unShow !== null ? formValue.unShow : false;
  }
  filterBrands(event) {
    this.results = [];
    for (let i = 0; i < this.tags.length; i++) {
      let brand: Tag = this.tags[i];
      if (brand.tagName.toLowerCase().indexOf(event.query.toLowerCase()) >= 0) {
        this.results.push(brand);
      }
    }
    this.tagData = this.results.map(o => o.tagName);
  }

  handleDropdownClick(event) {
    this.results = [];
    setTimeout(() => {
      this.results = [...this.tags];
      this.tagData = this.results.map(o => o.tagName);
    }, 100)
  }

  //选择发生改变时，获取当前测点下的状态组
  onSelect(event) {
    let index = this.results.findIndex(o => o.tagName == this.brand);
    if (index > -1) {
      this.msGroups = this.parentEntity.msGroups.filter(o => o.tagId == this.results[index].tagId);
    }
  }
}



// WEBPACK FOOTER //
// ./src/app/module/basic/model/tag-map/tag-map-edit/tag-map-edit.component.ts